package com.yj.transport.service;

import com.yj.shipxy.service.ShipxyService;
import com.yj.shipxy.entity.ShipError;
import com.yj.shipxy.entity.ShipPosition;
import com.yj.shipxy.mapper.ShipErrorMapper;
import com.yj.transport.entity.TransportInfo;
import com.yj.transport.entity.TransportJournal;
import com.yj.transport.mapper.TransportInfoMapper;
import com.yj.transport.mapper.TransportJournalMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * Created by zhengguanyong on 2017/12/26.
 */
@Service
public class TaskTransportInfoService {

    @Autowired
    TransportInfoMapper transportInfoMapper;
    @Autowired
    TransportJournalService transportJournalService;
    @Autowired
    TransportJournalMapper transportJournalMapper;
    @Autowired
    ShipxyService shipxyService;
    @Autowired
    ShipErrorMapper shipErrorMapper;

    public void getLocalShipPosition() {
        List<TransportInfo> transportInfoList = transportInfoMapper.getShipTransportInfo();
        for (TransportInfo transportInfo: transportInfoList) {
            ShipPosition shipPosition = shipxyService.getPositionByKeyword(transportInfo.getPlate_number());
            if (shipPosition == null) {
                ShipError shipError = new ShipError();
                shipError.setTransport_info_id(transportInfo.getId());
                shipError.setPlate_number(transportInfo.getPlate_number());
                shipError.setUser_id(transportInfo.getUser_id());
                shipErrorMapper.createTransportJournal(shipError);
                continue;
            } else {
                TransportJournal transportJournal = new TransportJournal();

                BigDecimal lon = new BigDecimal(shipPosition.getLon()).divide(new BigDecimal(1000000));
                BigDecimal lat = new BigDecimal(shipPosition.getLat()).divide(new BigDecimal(1000000));
                String arrive_place = "坐标"+lon+","+lat;
                if (transportJournalMapper.getJournalDetailByPlace(transportInfo.getId(),arrive_place) != null) {
                    continue;
                }
                transportJournal.setTransport_info_id(transportInfo.getId());
                transportJournal.setTransport_type(3);
                transportJournal.setArrive_place(arrive_place);
                LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(shipPosition.getLasttime(),0, ZoneOffset.ofHours(8));
                transportJournal.setArrive_time(localDateTime);
                transportJournal.setPlace_type(1);
                transportJournal.setLongitude(lon);
                transportJournal.setLatitude(lat);
                transportJournalService.createTransportJournal(transportJournal);
            }
        }
    }
}
